package com.rfsp.mcp.controller.base;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import com.rfsp.common.base.ResultVO;
import com.rfsp.common.log.TrcMsg;
import com.rfsp.common.util.FileUtil;
import com.rfsp.common.util.StringUtil;
import com.rfsp.mcp.controller.hos.HosAuthController;
import com.rfsp.mcp.pojo.po.FinancePO;
import com.rfsp.mcp.pojo.vo.AuthVO;
import com.rfsp.mcp.service.AuthService;
import com.rfsp.mcp.service.FinanceService;

@Controller("BaseAuthController")
@RequestMapping("/base/auth")
public class BaseAuthController extends BaseController{
	
	public Logger logger = LoggerFactory.getLogger(BaseAuthController.class);
	
	@Autowired
	AuthService authService;
	
	@Autowired
    FinanceService financeService;

	/**上传地址*/
    @Value("${mcp.file-pdf-path-auth}")
    private String filePDFPath;
    
    @GetMapping("/detail")
    public String detail(ModelMap model,Long id,String aid) {
    	logger.info(TrcMsg.getMsg(TrcMsg.METHOD_BEGIN, "detail"));
    	
        AuthVO authVO = authService.getById(id);
        logger.info("authVO="+authVO);
        if(authVO.getAid()!=null) {
            if (!authVO.getAid().equals(aid)) {
                return this.errorAidNotMatch(model);
            }
        }
        
        FinancePO financePO = financeService.getByAuthId(id);
        logger.info("financePO="+financePO);
        if(financePO != null) {
        	authVO.setFinanceId(financePO.getId());
        }
        
        authVO.setFilePath("/mcp/base/auth/download/?id="+authVO.getId());
        ResultVO<AuthVO> result = ResultVO.success(authVO);
        model.put("vo", result);
        
        
        logger.info(TrcMsg.getMsg(TrcMsg.METHOD_END, "detail"));
        return "base/auth/detail";
    }
    
    @RequestMapping("/download")
    public String download(HttpServletRequest request, HttpServletResponse response, ModelMap model,Long id) {
    	
        AuthVO authVO = authService.getById(id);
        
    	String dirPath = filePDFPath.replaceFirst("date", StringUtil.dateToString(authVO.getAuthCreateTime(), "yyyy/MM/dd/")) + authVO.getAuthNo() + ".pdf";
        authVO.setFilePath(dirPath);
        
        
        try {
			FileUtil.downloadfile(request, response, dirPath, authVO.getAuthNo()+".pdf");
		} catch (Exception e) {
			e.printStackTrace();
		}
        

        return null;
    }
}